<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\AppAccountLog;
use app\common\model\BetsLog;
use app\common\model\BetsLogSubscribe;
use app\common\model\BonusLog;
use app\common\model\EthAccount;
use app\common\model\EthAccountLog;
use app\common\model\GamblerKing;
use app\common\model\GamblerKingAction;
use app\common\model\GamblerKingInvestmentUser;
use app\common\model\GamesDailyLog;
use app\common\model\GamesLog;
use app\common\model\KingAccountLog;
use app\common\model\Lottery;
use app\common\model\LotteryPlay;
use app\common\model\LotteryPlayType;
use app\common\model\LotteryResult;
use app\common\model\LotteryRound;
use app\common\model\LotteryType;
use app\common\model\Member;
use app\common\model\PlanNumber;
use app\common\model\ThirdPlanProgramme;
use app\common\model\ThirdPlanUserProgramme;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserKingInvestment;
use app\common\model\Wallet;
use app\common\model\WithdrawalPayinfo;
use think\Db;

/**
 * 用户接口逻辑
 */
class Game extends ApiBase
{


    /***
     * 玩法列表
     */
    public function play_list($data){
        empty($data['cate_id'])  && $data['cate_id']=5;
        empty($data['is_old'])  && $data['is_old']=0;
        $play_type_list=LotteryPlayType::all();
        $list=$arr=[];
        $point=getConfig('max_point');
        $member=$this->logicApiBase->member;
        $game_return=$member->level->game_return;
        foreach ($play_type_list as $k=>$v){
            $arr['name']=$v['name'];
            $arr['id']=$v['id'];
            $arr['status']=$v['status'];
            $arr['description']=$v['description'];
            $arr['point']=$point;
            $arr['list']=LotteryPlay::where(['cate_id'=>$data['cate_id'],'play_cate_id'=>$v['id'],'is_old'=>$data['is_old']])->select();
            if($arr['list']){
                foreach ($arr['list'] as $ke=>$va){
                    $arr['list'][$ke]['new_mult']=format_money($va->mult/getConfig('max_point')*$game_return,4);
                }
                $list[]=$arr;
            }
        }
        return $list;
    }

    /***
     * 彩种列表
     */
    public function lottery_list($data){
        $where=['status'=>1];
        !empty($data['cate_id']) && $where['cate_id']=$data['cate_id'];
        $list=Lottery::where($where)->order('sort desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->image;
        }
        return $list;
    }

    /***
     * 彩种分类表
     */
    public function lottery_cate($data){
        $list=LotteryType::where(['status'=>1])->order('sort desc')->select();
        return $list;
    }



    /***
     * 开奖列表
     */
    public function lottery_result($data){
        $re_list=LotteryResult::where(['status'=>1,'lottery_id'=>$data['lottery_id']])->order('id desc')->limit(10)->select();
        $color = array(
            '01'=>'#F76DE2',
            '02'=>'#FE7501',
            '03'=>'#5333FF',
            '04'=>'#0191E1',
            '05'=>'#780A01',
            '06'=>'#E6DE00',
            '07'=>'#B26DF7',
            '08'=>'#16C408',
            '09'=>'#FF4E00',
            '10'=>'#A77B7B',
            '11'=>'#613038',
        );
        $list = array();
        foreach($re_list as $k => $v){
//            if($v['lottery_id']>1){
//                $arr=explode(",",$v['number']);
//                sort($arr);
//
//            }else{
            $arr = explode(",",$v['number']);
//            }
            $list[$k]['day_round'] = $v['day_round'];
            $list[$k]['round'] = $v['round'];
            $list[$k]['dateline'] = $v['dateline'];
            $list[$k]['number']=$arr;
            foreach($arr as $arr_k => $arr_v){
                $dat['number'] = $arr_v;
                $dat['color'] = $color[$arr_v];

                $list[$k]['list'][] = $dat;
            }

        }
        return $list;
    }


    /***
     *开奖结果
     */
    public function  lottery_result_log($data){
        $where['a.status']=1;
        !empty($data['id'])  && $where['a.cate_id']=$data['id'];
        $join = [

            [ '__LOTTERY_RESULT__ c', 'a.id = c.lottery_id'],
        ];


        $this->modelLottery->alias('a');
        $this->modelLottery->join = $join;
        $this->modelLottery->group = 'a.id';
        $lottery_list=$this->modelLottery->getList($where,'a.id,a.name','a.sort desc ,a.id desc');
        foreach ($lottery_list as $k=>$v){
            $result=LotteryResult::where(['lottery_id'=>$v['id']])->order('id desc')->find();

            $lottery_list[$k]['round']=$result['round'];
            $lottery_list[$k]['number']=explode(',',$result['number']);
            $lottery_list[$k]['add_time']=date('m-d H:i',$result->getData('create_time'));
        }
        return $lottery_list;



    }


    /***
     *更多开奖结果
     */
    public function  more_lottery_result_log($data){
        $where['a.status']=1;
        !empty($data['id'])  && $where['a.lottery_id']=$data['id'];
        $this->modelLotteryResult->alias('a');
        $lottery_list=$this->modelLotteryResult->getList($where,'*','a.id desc');
        foreach ($lottery_list as $k=>$v){

            $lottery_list[$k]['number']=explode(',',$v['number']);
            $lottery_list[$k]['add_time']=date('m-d H:i',$v->getData('create_time'));
        }
        return $lottery_list;



    }

    /***
     * 当前开奖期数
     */

    public function lottery_info($data){
        LotteryRound::where("start_time <= unix_timestamp(now()) and state=1 ")->update(["state" => 2]);
        LotteryRound::where("end_time < unix_timestamp(now()) ")->update(["state" => 3]);
        $info=LotteryRound::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'state'=>2])->order('id desc')->find();
        if(!$info){
            $info=LotteryRound::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'state'=>1,'start_time'=>['gt',TIME_NOW]])->order('id asc')->find();
        }
        if($info){
            $info['start_time_down']=$info->getData('start_time')-TIME_NOW;
            $info['end_time_down']=$info->getData('end_time')-TIME_NOW;
        }

        return $info;
    }

    /***
     * 下注接口
     */
    public function  one_key_lottery_bet($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $list=json_decode(htmlspecialchars_decode(html_entity_decode($data['data'])),true);
        if(!$list){
            return ajaxreturn(1,lang('参数错误'));
        }
        Db::startTrans();
        try{
            foreach ($list as $k=>$v){
                $play=LotteryPlay::get($v['play_id']);
                if(!$play){
                    Db::rollback();
                    return ajaxreturn(1,lang('玩法错误'));
                }
                $lottery=Lottery::get($v['lottery_id']);
                if(!$lottery){
                    Db::rollback();
                    return ajaxreturn(1,lang('彩种错误'));
                }

                $lottery_info=LotteryRound::get(['lottery_id'=>$v['lottery_id'],'round'=>$v['round']]);
                if(!$lottery_info){
                    Db::rollback();
                    return ajaxreturn(1,lang('期号错误'));
                }
                if($lottery_info['state']!=2){
                    Db::rollback();
                    return ajaxreturn(1,lang('当前期数未开始'));
                }


                $v['user_id']=$uid;
                $res=$play->new_add_lottery($v);
                if($res['status']==1){
                    Db::rollback();
                    return ajaxreturn(1,lang($res['msg']));
                }



            }
            Db::commit();
            return ajaxreturn(0,lang($res['msg']));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }

    }


    /***
     * 计算奖金和返点
     */
    public function compute_lottery($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $play=LotteryPlay::get($data['play_id']);
        if(!$play){
            return ajaxreturn(1,lang('玩法错误'));
        }
        $lottery=Lottery::get($data['lottery_id']);
        if(!$lottery){
            return ajaxreturn(1,lang('彩种错误'));
        }

        if($play->is_old==1){
            $arr['injection_number']=$counts =1;
        }else{
            $cate_symbol=$play->cate->symbol;
            include_once(ROOT_PATH.'extend/yzwanfa/'.$cate_symbol.'.php');
            $_zhushuyzclass = "Lib\\yzwanfa\\{$cate_symbol}";
            $play_obj= new $_zhushuyzclass();
            $arr['injection_number']=$counts=$play_obj->checkzhushu($play->symbol,$data['parameter']);
            if(empty($counts)){
                return ['status'=>1,'msg'=>'下注参数错误'];
            }

        }
        $arr['capitals']=$capitals= $data['univalent'] * $counts*$data['mult'];//本金
        $userinfo=Member::get($uid);
        if(strstr($play->max_reward, '|') && strstr($play->max_reward, '|')){
            $userinfo=Member::get($uid);
            $v1 = explode('|', $play->max_reward);  //最大奖金
            $v2 = explode('|', $play->max_reward);  //最小奖金
            $maxjj = "";
            //echo $userinfo['fandian'];exit;
            foreach ($v1 as $j => $val) {
                $maxstr = ((($v1[$j] - $v2[$j]) / getConfig('max_point')) * $userinfo->level['game_return'] + $v2[$j]) . '|';
                $maxjj .= sprintf("%.2f", filter_money($maxstr, 2)) . '|';
            }
            $maxjj = substr($maxjj, 0, -1);
            $arr['rate']=$rate = $maxjj*$data['univalent'];
        }elseif($play->max_reward>0 && $play->min_reward>0){

            $maxjj = ($play->max_reward - $play->min_reward>0) / (getConfig('max_point')) * ($userinfo->level['game_return']) + $play->min_reward;
            if (substr(explode('.', $maxjj)[1], 0, 2) == '99') {
                $maxjj = sprintf("%.2f", ceil($maxjj));
            } else {
                $maxjj = sprintf("%.2f", filter_money($maxjj, 2));
            }
            $arr['rate']=$rate = $maxjj*$data['univalent'];
        }else{
            $arr['rate']=$rate=$play->mult/getConfig('max_point')* $userinfo->level['game_return']*$data['univalent'];

        }

        $arr['point_money']=$point_money=0;
        if ($data['point_odds']) {

            $arr['rate'] = ($rate -    sprintf("%.2f",$arr['rate']  / 100 * $data['point_odds']));
            $arr['point_money']=$data['point_odds']* $arr['capitals']/100;
        }
        $arr['rate']=format_money($data['mult']*$arr['rate'],4);
        return $arr;
    }

    /***
     * 下注接口
     */
    public function  new_lottery_bet($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $play=LotteryPlay::get($data['play_id']);
        if(!$play){
            return ajaxreturn(1,lang('玩法错误'));
        }
        $lottery=Lottery::get($data['lottery_id']);
        if(!$lottery){
            return ajaxreturn(1,lang('彩种错误'));
        }

        $lottery_info=LotteryRound::get(['lottery_id'=>$data['lottery_id'],'round'=>$data['round']]);
        if(!$lottery_info){
            return ajaxreturn(1,lang('期号错误'));
        }
        if($lottery_info['state']!=2){
            return ajaxreturn(1,lang('当前期数未开始'));
        }
        Db::startTrans();
        try{
            $data['user_id']=$uid;
            $res=$play->new_add_lottery($data);
            if($res['status']==1){
                Db::rollback();
                return ajaxreturn(1,lang($res['msg']));
            }
            Db::commit();
            return ajaxreturn(0,lang($res['msg']));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }
    }
    /***
     * 预约下注期数接口
     */
    public function  subscribe_lottery_round($data){
        $lottery=Lottery::get($data['lottery_id']);
        if(!$lottery){
            return ajaxreturn(1,lang('彩种错误'));
        }

        $info=LotteryRound::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'state'=>2])->order('id asc')->find();
        if(!$info){
            $info=LotteryRound::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'state'=>1,'start_time'=>['gt',TIME_NOW]])->order('id asc')->find();
        }
        $list=LotteryRound::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'round'=>['>=',$info['round']]])->order('id asc')->limit(8)->select();


        return $list;


    }

    /***
     * 预约下注接口
     */
    public function  subscribe_add_lottery($data){
        $uid=decoded_user_token($data['user_token'],'member_id');

        Db::startTrans();
        try{
            $list=json_decode(htmlspecialchars_decode(html_entity_decode($data['data'])),true);
            foreach ($list as $k=>$v){
                $play=LotteryPlay::get($v['play_id']);
                if(!$play){
                    Db::rollback();
                    return ajaxreturn(1,lang('玩法错误'));
                }
                $lottery=Lottery::get($v['lottery_id']);
                if(!$lottery){
                    Db::rollback();
                    return ajaxreturn(1,lang('彩种错误'));
                }

                $lottery_info=LotteryRound::get(['lottery_id'=>$v['lottery_id'],'round'=>$v['round']]);
                if(!$lottery_info){
                    Db::rollback();
                    return ajaxreturn(1,lang('期号错误'));
                }
                if($lottery_info['state']==3){
                    Db::rollback();
                    return ajaxreturn(1,lang('当前期数未开始'));
                }


                $v['user_id']=$uid;
                $v['is_synchro']=$data['is_synchro'];
                $res=$play->subscribe_add_lottery($v);
                if($res['status']==1){
                    Db::rollback();
                    return ajaxreturn(1,lang($res['msg']));
                }



            }
            Db::commit();
            return ajaxreturn(0,lang($res['msg']));
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }
    }


    /**
     * 投注记录
     */
    public function bet_log($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $where=['status'=>1,'user_id'=>$uid];
        if(!empty($data['type'])){
            switch ($data['type']){
                case 1:
                    //今天

                    $where['create_time']=['between',[getTodayStart(),getTodayEnd()]];
                    break;
                case 2:
                    //昨天
                    $where['create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];
                    break;
                case 3:
                    //  前天
                    $where['create_time']=['between',[getTodayStart()-86400*2,getTodayEnd()-86400*2]];

                    break;
                case 4:
                    //近7天
                    $where['create_time']=['between',[getTodayStart()-86400*7,getTodayEnd()-86400*7]];

                    break;
                case 5:

                    //近15天
                    $where['create_time']=['between',[getTodayStart()-86400*15,getTodayEnd()-86400*15]];

                    break;
                case 6:
//              //近30天
                    $where['create_time']=['between',[getTodayStart()-86400*30,getTodayEnd()-86400*30]];
                    break;
            }

        }

        !empty($data['state'])  && $where['state']=$data['state'];
        !empty($data['lottery_id'])  && $where['lottery_id']=$data['lottery_id'];
        if(!empty($data['start_time']) && !empty($data['end_time'])){

            $where['create_time']=['between',[strtotime($data['start_time'].' 00:00:00'),strtotime($data['end_time'].' 23:59:59') ]];
        }
        $member=$this->logicApiBase->member;
        $list=$this->modelBetsLog->getList($where,'*','id desc');
        foreach ($list as $k =>$v){
            $list[$k]['username']=$member['username'];

            $list[$k]['image']=$member->avtar;
            $list[$k]['cancel_time']=$v->getData('create_time')+20-TIME_NOW;
            if($v['is_old']==1){
                $list[$k]['play_name']=$v->play->playcate->data['name'].'-'.$v->play->data['name'];
            }else{
                $list[$k]['play_name']=$v->play->data['name'];
            }

            $list[$k]['lottery_name']=$v->lottery->data['name'];
            $list[$k]['lottery_image']=$v->lottery->image;
            unset($v->play);
            unset($v->lottery);
            $list[$k]['result_number']=LotteryResult::where(['round'=>$v['round'],'lottery_id'=>$v['lottery_id']])->value('number');
        }
        return $list;
    }

    /**
     * 走势
     */
    public function bet_trend($data){
        $re_list=LotteryResult::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->order('id desc')->limit($data['list_rows'])->page($data['page'])->select();
        $count=LotteryResult::where(['status'=>1,'lottery_id'=>$data['lottery_id'],'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->count();
        $last_page=ceil($count/$data['list_rows']);
        $re_list = array_reverse($re_list);
        foreach ($re_list as $k=>$v){
            $re_list[$k]['result_number']=explode(',',$v['number']);
            if(!empty($data['type'])){
                foreach ($re_list[$k]['result_number'] as $ke=>$va){
                    if($data['type']-1==$ke){
                        $re_list[$k]['result_number']=$va;
                        break;
                    }
                }
            }
        }


        return ['total'=>$count,'per_page'=>$re_list,'current_page'=>$data['page'],'last_page'=>$last_page,'data'=>$re_list];
    }


    /**
     *查看游戏日志
     */
    public function game_log($data){
        $list=$this->modelGamesLog->getList(['user_investment_id'=>$data['id'],'type'=>4]);
        foreach ($list as $k=>$v){
            if($v['state']==4){
                $list[$k]['reward_state'] =(int)$v['profit']>0?2:3;
            }else{
                $list[$k]['reward_state'] =1;
            }
            $list[$k]['bet_number']=$v->bets->number;
            if($v->bets['is_old']==1){
                $list[$k]['play_name']=$v->bets->play->playcate->data['name'].'-'.$v->bets->play->data['name'];
            }else{
                $list[$k]['play_name']=$v->bets->play->data['name'];
            }

            $list[$k]['round']=$v->bets->round;
            unset($v->bets);
        }

        return $list;

    }

    /***
     * 游戏日志详情
     */
    public function  game_info($data){
        $game_info=GamesLog::get($data['id']);
        $info=[];
        switch ($game_info['game_type']){
            case 1:
                $info=BetsLog::get(['trade_no'=>$game_info['order_no']]);
                $info['lottery_name']=$info->lottery->data['name'];
                if(strstr($info->number, ',')){
                    $info['play_name']=$info->play->data['name'];
                }else{
                    $info['play_name']=$info->play->data['name'].'-'.$info['number'];
                }

                $info['king_name']=$info->king->data['name'];
                $info['result_number']=LotteryResult::where(['round'=>$info['round'],'lottery_id'=>$info['lottery_id']])->value('number');
                unset($info->lottery);
                unset($info->play);
                unset($info->king);
                break;

        }

        return $info;
    }

    /**
     * 游戏撤单
     */
    public function cancel_order($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $member=$this->logicApiBase->member;
        Db::startTrans();
        $ids=explode(',',$data['id']);


        try{
            foreach ($ids as $k=>$v){
                $info=BetsLog::where(['id'=>$v])->lock(true)->find();
                if(!$info){
                    Db::rollback();
                    return ajaxreturn(1,lang('订单不存在'));
                }
                if($info->getData('create_time')+20<=TIME_NOW){
                    Db::rollback();
                    return ajaxreturn(1,lang('当前时间已超出撤单时间'));
                }
                if($info['state']!=1){
                    Db::rollback();
                    return ajaxreturn(1,lang('订单状态错误'));
                }
                $info->state=4;
                $info->save();
                GamesLog::where(['order_no'=>$info['trade_no']])->delete();
                if($info['king_id']>0){
                    $king=GamblerKing::where(['id'=>$info['king_id']])->lock(true)->find();
                    $king->balance+=$info['king_money'];
                    $king->king_win_account+=$info['money'];
                    $king->save();
                    //写入流水
                    KingAccountLog::create([
                        'user_id'=>$uid,
                        'king_id'=>$info['king_id'],
                        'number'=>$info['king_money'],
                        'before_blance'=>$king->balance-$info['money'],
                        'after_blance'=>$king->balance,
                        'remark'=>'撤单退回',
                        'type'=>4
                    ]);
                }else{
                    //撤单
                    $user_account=UserAccount::check(['user_id'=>$uid,'wallet_id'=>1],false);

                    $user_account->balance+=$info['money'];
                    $user_account->save();
                    //写入流水
                    UserAccountLog::create([
                        'user_id'=>$uid,
                        'wallet_id'=>1,
                        'before_blance'=>$user_account->balance-$info['money'],
                        'after_blance'=>$user_account->balance,
                        'remark'=>'撤单返还',
                        'is_add'=>1,
                        'number'=>$info['money'],
                        'type'=>31,
                    ]);

                }
                //减少业绩
                //等级降级
                $member->lei_money-=$info['money'];
                $member->save();
                $member->downgrade($info['money']);
                UserKingInvestment::where(['id'=>$data['id']])->update(['state'=>2,'update_time'=>time()]);

            }

            Db::commit();
            return ajaxreturn(0,'撤单成功');
        }catch (\Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
        }
    }

    /**
     * 我的理财统计
     */

    public function  my_investment_statistics($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $info['total_count']=UserKingInvestment::where(['user_id'=>$uid,'state'=>['in',[0,4,5,6,7,8]]])->count();
        $info['total_money']=UserKingInvestment::where(['user_id'=>$uid,'state'=>['in',[0,4,5,6,7,8]]])->sum('money')+0;
        $info['conduct_total_money']=UserKingInvestment::where(['user_id'=>$uid,'state'=>['in',[0,5,6]]])->sum('money')+0;
        $info['profit']=BonusLog::where(['type'=>2,'user_id'=>$uid,'number'=>['gt',0]])->sum('number')+0;
        $info['lose_money']=UserKingInvestment::where(['user_id'=>$uid,'state'=>8])->sum('profit')+0;
        $info['bonus_total']=BonusLog::where(['type'=>2,'user_id'=>$uid,'number'=>['gt',0]])->sum('number')+0;
        $info['lose_total']=$this->logicApiBase->member['loss_bet'];
        $info['stop_lose_total']=$this->logicApiBase->member['app_balance'];
        $info['lose_count']=BonusLog::where(['type'=>2,'user_id'=>$uid,'number'=>['lt',0]])->count();
        $info['copy_count']=BonusLog::where(['type'=>2,'user_id'=>$uid,'number'=>['gt',0]])->count();
        $info['stop_lose_count']=BonusLog::where(['type'=>2,'user_id'=>$uid,'number'=>['lt',0]])->count();
        $info['app_money']=$this->logicApiBase->member['app_balance'];

        $info['user_reward_money']=GamesDailyLog::where(['type'=>2,'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->sum('number')+0;
        $info['user_bets_money']=GamesDailyLog::where(['type'=>2,'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->sum('number')+0;

        $info['my_reward_money']=GamesDailyLog::where(['user_id'=>$uid,'type'=>2])->sum('number')+0;
        $info['my_bets_money']=GamesDailyLog::where(['user_id'=>$uid,'type'=>1])->sum('number')+0;
        // $where=['state'=>['in',[2,3]]];
        if(!empty($data['type'])){
            switch($data['type']){
                case  1:
                    //今日
                    $where['create_time']=['between',[getTodayStart(),getTodayEnd()]];

                    break;
                case  2:
                    //昨日
                    $where['create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];
                    break;
                case  3:
                    //近七天
                    $where['create_time']=['between',[getTodayStart()-86400*7,getTodayEnd()]];
                    break;
                case  4:
                    //近30天
                    $where['create_time']=['between',[getTodayStart()-86400*30,getTodayEnd()]];


                    break;


            }
        }
        $where['type']=1;
        $king_bets_money=GamesDailyLog::where($where)->sum('king_lose_number')+0;
        $info['king_bets_money']=arrangement_total($king_bets_money);
        $info['total_bets_money']=arrangement_total(GamesDailyLog::where($where)->sum('user_lose_number')+ $king_bets_money);
        $where['type']=2;
        $info['total_reward_money']=arrangement_total(GamesDailyLog::where($where)->sum('number')+0);
        return $info;

    }


    /**
     * 游戏收益统计
     */
    public function  bet_statistics($data){
        $uid=decoded_user_token($data['user_token'],'member_id');
        $king=$this->modelGamblerKing->field('name,balance,king_win_account,stop_lose_account,id,credit_score,tags,user_id')->where(['user_id'=>$uid,'status'=>1,'state'=>2])->find();
        if(!$king){
            return  ajaxreturn(1,lang('您不是赌王'));
        }
        $info=[];
        $info['balance']=$king['balance'];
        $info['balance_do']=$king['king_win_account'];
        $user_invesment=GamblerKingInvestmentUser::get($data['user_investment_id']);

        $lose_money=GamesLog::where(['user_investment_id'=>$data['user_investment_id'],'type'=>4,'state'=>4])->sum('profit')+0;
        $info['profit']=$lose_money;
        $bet_money=BetsLog::where(['user_investment_id'=>$data['user_investment_id'],'state'=>['neq',4]])->sum('money')+0;
        $info['bet_money']=$bet_money;
        
        // $info['profit_percentage']=format_money($info['profit']/( $user_invesment['surplus_money']+$king->balance )*100,2);
        $info['profit_percentage']=format_money($info['profit']/( $user_invesment['surplus_money']+$user_invesment['price'])*100,2);
        $info['bets_count']=BetsLog::where(['user_investment_id'=>$data['user_investment_id'],'state'=>['neq',4]])->count();
        $info['reward_count']=BetsLog::where(['user_investment_id'=>$data['user_investment_id'],'state'=>2])->count();
        $info['loss_count']=BetsLog::where(['user_investment_id'=>$data['user_investment_id'],'state'=>3])->count();

        return $info;
    }

    /**
     * 继续购买
     */
    public function bet_again($data){
        $bet=BetsLog::get($data['id']);
        if(!$bet){
            return  ajaxreturn(1,lang('下注记录不存在'));
        }
        if($bet['state']!=1){
            return  ajaxreturn(1,lang('该期号已结束'));
        }
        if($bet['king_id']>0){
            return  ajaxreturn(1,lang('委托单不能再次购买'));
        }
        Db::startTrans();
        //用户下注
        $capitals=$bet['money'];
        try{
            $user_account=UserAccount::check(['user_id'=>$bet['user_id'],'wallet_id'=>1],false);
            if($user_account['balance']<$capitals){
                return  ajaxreturn(1,lang('总包余额不足'));

            }
            $user_account->balance-=$capitals;
            $user_account->save();
            //写入流水
            UserAccountLog::create([
                'user_id'=>$bet['user_id'],
                'wallet_id'=>1,
                'before_blance'=>$user_account->balance+$capitals,
                'after_blance'=>$user_account->balance,
                'remark'=>'用户再次下注'.$bet['round'].'期',
                'number'=>$capitals,
                'type'=>29,
                'is_add'=>2,
            ]);

            //插入订单
            $dat = array(
                'user_id'=>$bet['user_id'],
                'lottery_id'=>$bet['lottery_id'],
                'play_id'=>$bet['play_id'],
                'round'=>$bet['round'],
                'number'=>$bet['number'],
                'injection_number'=>$bet['injection_number'],
                'user_investment_id'=>0,
                'mult'=>$bet['mult'],
                'univalent'=>$bet['univalent'],
                'entrust_count'=>0,
                'king_id'=>0,
                'state'=>1,//1待开奖  2中奖 3:未中
                'money'=>$capitals,   //本金
                'create_time'=>TIME_NOW,
                'odds'=>$bet['odds'],
                'point_odds'=>$bet['point_odds'],
                'return_point_money'=>$bet['return_point_money'],
                'is_old'=>$bet['is_old'],
                'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),

            );

            $game=[
                'user_id'=>$bet['user_id'],
                'king_id'=>0,
                'user_investment_id'=>0,
                'investment_id'=>0,
                'type'=>4,
                'entrust_count'=>0,
                'state'=>3,
                'order_no'=>$dat['trade_no'],
                'number'=>$capitals,
                'create_time'=>TIME_NOW,
                'users'=>''
            ];
            Db::name('bets_log')->insert($dat);
            Db::name('games_log')->insert($game);
            Db::commit();
            return  ajaxreturn(0,lang('购买成功'));
        }catch (\Exception $e){
            Db::rollback();
            return  ajaxreturn(1,$e->getMessage());
        }

    }


    /***
     *大数据云预测库
     */

    public function third_plan_list($data){
        $where['status']=1;
        $where['lottery_id']=$data['lottery_id'];
        $where['play_id']=$data['play_id'];
//        !empty($data['code_number'])  &&   $where['code_number']=$data['code_number'];
        $list=$this->modelThirdPlan->getList($where,'*','id desc');

        foreach ($list as $k=>$v){
            $info=PlanNumber::where(['plan_id'=>$v['id']])->order('id desc')->find();
            $list[$k]['currency_round']=$info['end_round'];
        }
        return $list;
    }

    /**
     * 方案号码
     */
    public function plan_number($data){
        $where['plan_id']=$data['plan_id'];
        !empty($data['play_id'])  &&   $where['play_id']=$data['play_id'];
//        !empty($data['code_number'])  &&   $where['code_number']=$data['code_number'];
        $list=$this->modelPlanNumber->getList($where,'*','id desc');
        foreach ($list as $k=>$v){
            $list[$k]['reward_rate']=$v->reward_rate;
            $end_round=$v['first_number']+$data['round']-1;
            if($end_round>$v->lottery->round_number){
                $end_round-=$v->lottery->round_number;
            }
            $list[$k]['number']=str_replace('|','',$v['number']);
            $list[$k]['plan_round']=$v['first_number'].'-'.$end_round;
            unset($v->lottery);
            $res_round=LotteryResult::where(['lottery_id'=>$v['lottery_id'],'round'=>$v['reward_round']])->value('number');
            if($res_round){

                $list[$k]['lottery_result']= $res_round;
            }else{
                $bets=BetsLogSubscribe::where(['plan_number_id'=>$v['id']])->order('id desc')->value('round');
                $list[$k]['lottery_result']= LotteryResult::where(['lottery_id'=>$v['lottery_id'],'round'=>$bets])->value('number');
            }
        }
        return $list;
    }

    /**
     * 方案详情
     */

    public function  plan_detail($data){
        $info=\app\common\model\ThirdPlan::get($data['id']);
        if(!$info){
            return  ajaxreturn(1,lang('方案不存在'));
        }
        $where['status']=1;
        $where['lottery_id']=$info['lottery_id'];
        $lottery_info=$this->modelLotteryResult->where($where)->order('id desc')->find();

        $lottery_round=$this->modelLotteryRound->where(['round'=>$lottery_info['round']+1,'lottery_id'=>$info['lottery_id']])->order('id desc')->find();
        if(!$lottery_round){
            $lottery_round=$this->modelLotteryRound->where(['state'=>1,'lottery_id'=>$info['lottery_id']])->order('id asc')->find();
        }
        $arr['lottery_name']=$info->lottery->data['name'];
        $arr['round']=$lottery_info->round;
        $arr['create_time']=$lottery_info->create_time;
        $arr['number']=explode(',',$lottery_info['number']);
        $arr['down_time']=$lottery_round->getData('end_time')-TIME_NOW;
        $arr['has_round']=$lottery_info->day_round;
        $arr['surplus_round']=$info->lottery->round_number-$arr['has_round'];
        $arr['forecast_lose_count']=$info->forecast_lose_count;
        $arr['forecast_success_cycle']=$info->forecast_success_cycle;
        $arr['forecast_accuracy_rate']=$info->forecast_accuracy_rate;
        $arr['forecast_max_win']=$info->forecast_max_win;
        $arr['forecast_max_continuous_error']=$info->forecast_max_continuous_error;
        $arr['forecast_current_win']=$info->forecast_current_win;
        return $arr;

    }

    /***
     * 对冲保险模式
     */
    public function dedge_insurance_model($data){
        $member=$this->logicApiBase->member;
        $investment=GamblerKingInvestmentUser::get($data['id']);

        if(!$investment){
            return  ajaxreturn(1,lang('产品不存在'));
        }
        if($investment['state']!=2){
            return  ajaxreturn(1,lang('产品状态错误'));
        }
        $plan_ids=explode(',',$data['plan_ids']);
        $arrs=[];
        Db::startTrans();
        try{
            $order_count=GamblerKingInvestmentUser::where(['king_id'=>$investment['king_id'],'state'=>3])->count();
            if($order_count>0){
                return ajaxreturn(1,lang('您有一个产品的委托订单在游戏中，不能开始游戏游戏，请结束结束后操作'));
            }
            $investment->state=3;
            $investment->pattern=2;
            $investment->settlement_time=TIME_NOW+$investment->investment->cycle*86400;

            $account=UserAccount::check(['wallet_id'=>1,'user_id'=>$member['id']],false);
            $king=$this->modelGamblerKing->where(['user_id'=>$member['id'],'status'=>1,'state'=>2])->find();
            $number=$investment['king_win_account']/$investment['order_count'];
            if($number>$account['balance']){
                return ajaxreturn(1,lang('总包余额不足,无法接单，还需').format_money($number-$account['balance']).lang('元才能接单'));
            }

            //扣除用户总包余额
            $account->balance-=$number;
            $account->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$member['id'],
                'number'=>$number,
                'wallet_id'=>$account['wallet_id'],
                'before_blance'=>$account->balance+$number,
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'remark'=>'交易员对冲模式接单自动转入转入交易员余额',
                'type'=>16
            ]);

            $king->king_win_account+=$number;
            $king->balance+=$number;
            //写入资金流水
            KingAccountLog::create([
                'user_id'=>$member['id'],
                'number'=>$number,
                'king_id'=>$king['id'],
                'before_blance'=>$king->balance+$number,
                'after_blance'=>$king->balance,
                'is_add'=>1,
                'remark'=>'交易员接单自动转入转入交易员余额',
                'type'=>2
            ]);

            $king->stop_lose_account=$investment['stop_lose_account'];
            $king->king_win_account=$investment['king_win_account']+$number;
            $king->save();
            UserKingInvestment::where(['user_investment_id'=>$data['id'],'state'=>5])->update(['state'=>6]);
            $king_action=[
                'king_id'=>$investment->king_id,
                'user_investment_id'=>$investment->id,
                'cover_id'=>$investment->user->cover_id,
                'content'=>'我要开始交易啦',
                'type'=>2
            ];
            $user_ids= UserKingInvestment::where(['user_investment_id'=>$data['id'],'state'=>6])->column('user_id');
            $leader_ids=Member::where(['id'=>['in',$user_ids]])->group('leader_id')->column('leader_id');
            $mem=new Member();
            $mem->upgrade_level($leader_ids);
            GamblerKingAction::create($king_action);
            $investment->save();




            foreach ($plan_ids as $k=>$v){
                $plan=\app\common\model\ThirdPlan::get($v);
                if(!$plan){
                    return  ajaxreturn(1,lang('方案不存在'));
                }
                $plan=[
                    'user_id'=>$investment['user_id'],
                    'user_investment_id'=>$investment['id'],
                    'plan_id'=>$v,
                    'create_time'=>TIME_NOW
                ];
                $plans[]=$plan;
            }

            ThirdPlanProgramme::insertAll($plans);

            if($data['profit_condition']==2){
                $money=explode(',',$data['daily_profit']);
                if(!$money){
                    return  ajaxreturn(1,lang('收益设定错误'));
                }
            }else{
                if($data['daily_profit']<=0){
                    return  ajaxreturn(1,lang('收益设定错误'));
                }
            }
            if($data['double_condition']==2){
                $double=explode(',',$data['double_text']);
                if(!$double){
                    return  ajaxreturn(1,lang('倍数条件错误'));
                }
            }
            $data['user_investment_id']=$data['id'];
            $data['user_id']=$member['id'];
            unset($data['id']);

            $this->modelThirdPlanUserProgramme->setInfo($data);



           Db::commit();
            return  ajaxreturn(0,lang('保存成功'));

        }catch (\Exception $e){
            Db::rollback();
            return  ajaxreturn(1,$e->getMessage());
        }
    }


    /***
     *对冲计划列表
     */
    public function  investment_plan($data){
        $plan_programme=ThirdPlanProgramme::all(['user_investment_id'=>$data['id']]);
        $user_plan_programme=ThirdPlanUserProgramme::get(['user_investment_id'=>$data['id']]);
        foreach ($plan_programme as $k=>$v){
            if($v['first_round']==0){
                $plan_programme[$k]['round']='暂未开始';
            }else{
                $plan_programme[$k]['round']=$v['first_round'].'-'.$v['end_round'];
            }
            $plan_programme[$k]['profit_condition']=$user_plan_programme['profit_condition'];
            $plan_programme[$k]['is_simulation']=$user_plan_programme['is_simulation'];
            $plan_programme[$k]['bets_count']=BetsLog::where(['third_programme_id'=>$v['id'],'state'=>['neq',4],'user_investment_id'=>$data['id']])->count();
            $plan_programme[$k]['plan_name']=\app\common\model\ThirdPlan::where(['id'=>$v['plan_id']])->value('title');
            $plan_programme[$k]['code_number']=\app\common\model\ThirdPlan::where(['id'=>$v['plan_id']])->value('code_number');


        }
        return $plan_programme;
    }

    /**
     *查看游戏日志
     */
    public function investment_plan_game_log($data){
        $list=$this->modelGamesLog->getList(['third_programme_id'=>$data['id'],'type'=>4]);
        foreach ($list as $k=>$v){
            if($v['state']==4){
                $list[$k]['reward_state'] =(int)$v['profit']>0?2:3;
            }else{
                $list[$k]['reward_state'] =1;
            }
            $list[$k]['bet_number']=$v->bets->number;
            $list[$k]['bet_state']=$v->bets->state;
            $list[$k]['mult']=$v->bets->mult;
            if($v->bets['is_old']==1){
                $list[$k]['play_name']=$v->bets->play->playcate->data['name'].'-'.$v->bets->play->data['name'];
            }else{
                $list[$k]['play_name']=$v->bets->play->data['name'];
            }

            $list[$k]['round']=$v->bets->round;
            unset($v->bets);
        }

        return $list;

    }

    /**
     * 停止开启计划
     */
    public function edit_investment_plan($data){
        if($data['state']!=1 && $data['state']!=2){
            return  ajaxreturn(1,lang('状态错误'));
        }
        $plan_programme=ThirdPlanProgramme::get($data['id']);
        $plan_programme->state=$data['state'];
        $plan_programme->save();
        return  ajaxreturn(0,lang('修改成功'));
    }

    /**
     * 产品选择模式
     */
    public function edit_investment_pattern($data){
        if($data['state']!=1 &&  $data['state']!=2 && $data['state']!=3){
            return  ajaxreturn(1,lang('模式错误'));
        }
        $member=$this->logicApiBase->member;
        $king=$this->modelGamblerKing->getInfo(['user_id'=>$member['id'],'state'=>2]);
        if(!$king){
            return  ajaxreturn(1,lang('您不是交易员'));
        }

        $plan_programme=GamblerKingInvestmentUser::get($data['id']);
        if($plan_programme['user_id']!=$member['id']){
            return  ajaxreturn(1,lang('无权修改'));
        }

        $plan_programme->pattern=$data['state'];
        $plan_programme->save();
        return  ajaxreturn(0,lang('修改成功'));
    }

    /**
     * 关闭对冲挂机
     */
    public function close_investment_plan($data){

        $member=$this->logicApiBase->member;
        $king=$this->modelGamblerKing->getInfo(['user_id'=>$member['id'],'state'=>2]);
        if(!$king){
            return  ajaxreturn(1,lang('您不是交易员'));
        }

        $plan_programme=GamblerKingInvestmentUser::get($data['id']);
        if($plan_programme['user_id']!=$member['id']){
            return  ajaxreturn(1,lang('无权修改'));
        }
        ThirdPlanProgramme::where(['user_investment_id'=>$data['id']])->update(['state'=>2]);
        return  ajaxreturn(0,lang('修改成功'));
    }


}